import { HttpError, toSuccess, useEntityManager, useRedis } from "@sker/core"
import { KsDevice } from "@sker/entities"
import { useData } from "@sker/runtime"
import dayjs from "dayjs"

export default async () => {
    const body = useData()
    return await useEntityManager(async m => {
        const device = await m.findOne(KsDevice, { where: { uuid: body.uuid } })
        if (!device) throw new HttpError(`设备不存在或已删除`)
        if (!device.owner) throw new HttpError(`设备未激活绑定`)
        // 获取当日数据
        let today: any = {
            link: 0,
            successCount: 0,
            failCount: 0,
            redCount: 0
        }
        await useRedis(8, async r => {
            const key = `leader.${device.uuid}`
            const value = await r.get(key)
            if (value) {
                today = JSON.parse(value);
            } else {
                await r.set(key, JSON.stringify(today))
            }
            const endDate = dayjs().endOf('day').toDate().getTime()
            const expirationTime = Math.floor((endDate - new Date().getTime()) / 1000)
            await r.expire(key, expirationTime);
        });
        return toSuccess({
            id: device.id,
            uuid: device.uuid,
            owner: device.owner,
            ...device.setting,
            ...today
        })
    })
}
